Why is the value of __name__ changing after assignment to sys.modules[__name__]?
Posted
by
martineau
on Stack Overflow
See other posts from Stack Overflow
or by martineau
Published on 2011-03-19T23:13:49Z
Indexed on
2011/03/20
0:10 UTC
Read the original article
Hit count: 173
While trying to do something similar to what's in the ActiveState recipe titled Constants in Python by Alex Martelli, I ran into an unexpected side-effect that assigning a class instance to an entry in sys.modules
apparently has in Python 2.7 -- namely that doing so apparent changes the value of __name__
to None
as illustrated in the following code fragment:
class _test(object): pass
import sys
print '__name__: %r' % __name__
# __name__: '__main__'
sys.modules[__name__] = _test()
print '__name__: %r' % __name__
# __name__: None
if __name__ == '__main__': # never executes...
import test
print "done"
I'd like to understand why this is happening. I don't believe it was that way in Python 2.6 and earlier versions since I have some older code where apparently the if __name__ == '__main__':
conditional worked as expected following the assignment (but no longer does).
FWIW, I also noticed that the name _class
is getting rebound from a class object to None
, too, after the assignment. Also seems odd to me that they're being rebound to 'None' rather than disappearing altogether...
Update:
I'd like to add that any workarounds for achieving the effect of if __name__ == '__main__':
, given what happens would be greatly appreciated. TIA!
© Stack Overflow or respective owner